<?php

class Money_Model_DbTable_Orders extends Engine_Db_Table {

    protected $_rowClass = 'Money_Model_Order';

    public function setItem(Core_Model_Item_Abstract $resource, Core_Model_Item_Abstract $poster) {
        $table = $this->getOrderTable();
        $row = $table->createRow();

        if (isset($row->source_type)) {
            $row->source_type = $resource->getType();
        }

        $row->user_id = $poster->getIdentity();
        $row->state = 'pending';
        $row->creation_date = date('Y-m-d H:i:s');
        $row->source_id = $resource->getIdentity();

        if (isset($resource->comment_count)) {
            $resource->paid_count++;
            $resource->save();
        }
        $row->save();

        return $row;
    }

    public function getOrderTable() {
        return $this;
    }

    function getItemPaid(Core_Model_Item_Abstract $resource) {
        $viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity();
        if ($resource->getOwner()->getIdentity() == $viewer_id) {
            return true;
        }
        $table = $this->getOrderTable();
        $row = $table->select()
                ->from($table->info('name'), new Zend_Db_Expr('COUNT(*)'))
                ->where('source_type =?', $resource->getType())
                ->where('user_id =?', $viewer_id)
                ->where('source_id =?', $resource->getIdentity())
                ->where('state =?', 'complete')
                ->query()
                ->fetchColumn()
        ;
        if ($row) {
            return true;
        } else {
            return false;
        }
    }

}